package mess;

import java.util.*;

public class LeeCode_49 {
    public static void main(String[] args) {
        String[] strs = new String[]{"ddddddddddg","dgggggggggg"};
        System.out.println(groupAnagrams(strs));
    }
    private static List<List<String>> groupAnagrams(String[] strs) {
        int len = strs.length;
        List<List<String>> result = new ArrayList<>();
        Map<int[], List<String>> map = new HashMap<>();
        for (int i = 0; i < len; i++) {
            String s = strs[i];
            int lenS = s.length();
            int[] arr = new int[26];
            for (int j = 0; j < lenS; j++) {
                char c = s.charAt(j);
                int index = c - 97;
                arr[index] += 1;
            }
            if (!containsKey(map, arr)){
                //不存在的key
                List<String> list = new ArrayList<>();
                list.add(s);
                map.put(arr, list);
            }else {
                //已存在的key
                put(map, arr, s);
            }

        }

        Set<int[]> keys = map.keySet();
        for (int[] key : keys)
            result.add(map.get(key));
        return result;
    }

    private static boolean containsKey(Map<int[], List<String>> map, int[] arr){
        Set<int[]> keys = map.keySet();
        for (int[] key : keys) {
            if (Arrays.equals(key, arr))
                return true;
        }
        return false;
    }

    private static void put(Map<int[], List<String>> map, int[] arr, String s){
        Set<int[]> keys = map.keySet();
        for (int[] key : keys) {
            if (Arrays.equals(key, arr)) {
                map.get(key).add(s);
                break;
            }
        }
    }

}
